package com.noexcs.forum.event;

import com.alibaba.fastjson.JSONObject;
import com.noexcs.forum.entity.Event;
import com.noexcs.forum.entity.Message;
import com.noexcs.forum.service.MessageService;
import com.noexcs.forum.util.ForumConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

/**
 * @author noexcs
 * @since 6/4/2022 1:05 AM
 */
@Component
@Slf4j
public class EventConsumer implements ForumConstant {

    @Autowired
    MessageService messageService;

    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleCommentMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空！");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(),Event.class);
        if (event == null) {
            log.error("消息格式错误！");
        }

        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        HashMap<String, Object> content = new HashMap<>();
        content.put("userId",event.getUserId());
        content.put("entityType",event.getEntityType());
        content.put("entityId",event.getEntityId());

        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }




}
